package thingapi

import (
	"iot-base/common/dbconn"
	"iot-base/common/webapi"
	"strings"

	"github.com/gin-gonic/gin"
)

func makeCondtion(qmap map[string]string, cs *strings.Builder, mapTable map[string]int, ctype string, lore string) {
	if len(qmap) > 0 {
		if cs.Len() > 0 {
			cs.WriteString(" and ")
		}
		cs.WriteString("(")
		first := true
		for k, v := range qmap {
			p := strings.Split(k, ".")
			if len(p) == 2 {
				mapTable[p[0]] = 1
				if first {
					cs.WriteString(k + " " + lore + " " + v)
					first = false
				} else {
					cs.WriteString(" " + ctype + " " + k + " " + lore + " " + v)
				}

			}

		}
		cs.WriteString(" )")
	}

}

func initQueryAPI(r *gin.RouterGroup) {
	query := r.Group("queryEx")
	{
		query.GET("/", func(c *gin.Context) {
			mapTable := make(map[string]int)
			//cs := make([]string, 0, 5)
			var cs strings.Builder
			qmap := c.QueryMap("aeCondition") //and equal
			makeCondtion(qmap, &cs, mapTable, "and", "=")

			qmap = c.QueryMap("alCondition") //and like
			makeCondtion(qmap, &cs, mapTable, "and", "like")

			qmap = c.QueryMap("olCondition")
			makeCondtion(qmap, &cs, mapTable, "or", "like")

			qmap = c.QueryMap("oeCondition")
			makeCondtion(qmap, &cs, mapTable, "or", "=")

			if cs.Len() > 0 && len(mapTable) > 0 {
				var sel strings.Builder
				sel.WriteString("select ")
				var ts strings.Builder
				ts.WriteString(" from ")
				first := true
				for k := range mapTable {
					if !first {
						sel.WriteString(",")
						ts.WriteString(",")
					} else {
						first = false
					}
					sel.WriteString(k + ".*")
					ts.WriteString(k)
				}
				_, ok := mapTable["thing_params"]
				tr := ""
				if ok {
					tr = "things.uid = thing_params.thing_id and "
				}

				sql := sel.String() + " " + ts.String() + " where " + tr + cs.String()
				var result []map[string]interface{}
				err := dbconn.DBConnection.Raw(sql).Find(&result).Error
				if err != nil {
					webapi.SendError(err.Error(), webapi.DBError, c)
				} else {
					webapi.SendResult(result, nil, c)
				}
			}

		})
	}
}
